<template>
  <div class="electricity-case-content">
    <div class="header-btn-content">
      <el-button type="primary" plain :icon="SetUp" @click="handleMenu(0)">诊 断</el-button>
      <el-button type="primary" plain :icon="Camera" @click="handleMenu(1)">医 嘱</el-button>
      <el-button type="primary" plain :icon="Plus" @click="handleMenu(2)">添加病例</el-button>
      <el-button type="primary" plain :icon="Guide" @click="handleMenu(3)">添加流程</el-button>
      <el-button class="unlock-btn" type="warning" plain :icon="Document" @click="handleMenu(4)"
        >检测报告</el-button
      >
      <!-- <el-button class="unlock-btn" type="warning" plain :icon="Download" @click="handleMenu(5)"
        >导出Excel</el-button
      > -->
      <el-button class="unlock-btn" type="warning" plain :icon="Printer" @click="handleMenu(6)"
        >查看并打印</el-button
      >
      <el-button
        class="unlock-btn"
        type="warning"
        plain
        :icon="DocumentRemove"
        @click="handleMenu(7)"
        >电子病例文件</el-button
      >
    </div>
    <avue-crud
      :option="options"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu="{ row, index }">
        <el-button text plain @click="handleMenu(8, row, index)" style="color: #f39c12"
          >修改备注
        </el-button>
        <!-- <el-button text plain @click="handleMenu(9, row, index)" style="color: #00a65a"
          >PDF
        </el-button>
        <el-button text plain @click="handleMenu(10, row, index)" style="color: #00a65a"
          >XLS
        </el-button> -->
        <el-button text plain @click="handleMenu(11, row, index)" style="color: red"
          >删 除
        </el-button>
      </template>
      <template #name="{ row, index }">
        <span style="color: #72afd2; cursor: pointer" @click="handleMenu(12, row, index)">{{
          row.name
        }}</span>
      </template>
    </avue-crud>
    <el-dialog v-model="isElectricityCaseDialog" :title="electricityCaseDialogTitle" :width="electricityCaseDialogWidth" :top="electricityCaseDialogTop">
      <!-- clickMenuValue.type顶部按钮点击-type -->
      <div class="m-dialog-content" v-if="clickMenuValue.type === 0">
        <el-radio-group v-model="diagnoseRadio">
          <el-radio value="1" border>首次诊断</el-radio>
          <el-radio value="2" border>复 诊</el-radio>
        </el-radio-group>
      </div>
      <viewPrint v-if="clickMenuValue.type === 6" ref="viewPrintRef" />
      <electricityCaseFile v-if="clickMenuValue.type === 7" ref="electricityCaseFileRef" />
      <div class="edit-dialog-content" v-if="clickMenuValue.type === 8">
        <el-radio-group v-model="diagnoseRadio">
          <el-radio value="1" border>首次诊断</el-radio>
          <el-radio value="2" border>复 诊</el-radio>
          <el-radio value="3" border>医 嘱</el-radio>
          <el-radio value="4" border>检测报告</el-radio>
          <el-radio value="5" border>其 他</el-radio>
          <el-input
            v-if="diagnoseRadio === '5'"
            v-model="restInputValue"
            placeholder="请输入内容"
          ></el-input>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isElectricityCaseDialog = false">取 消</el-button>
          <el-button type="primary" @click="dialogSubmit" v-if="clickMenuValue.type != 6 && clickMenuValue.type != 7">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  SetUp,
  Camera,
  Plus,
  Guide,
  Document,
  Download,
  Printer,
  DocumentRemove,
} from '@element-plus/icons-vue';
import {
  eleMedicalRecordList,
  getDetail,
  add,
  update,
  remove,
  eleMedicalRecordSubmit,
  eleMedicalRecordRemove,
} from '@/api/casemanagement/caseManagement';
import electricityCaseFile from './electricityCaseFile'
import viewPrint from './viewPrint.vue'
import { findObject } from '@smallwei/avue';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const router = useRouter();
const store = useStore();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;
const crud = ref(null);
const form = ref({});
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const options = ref({
  height: 'auto',
  calcHeight: 30,
  tip: false,
  searchShow: true,
  searchMenuSpan: 24,
  searchMenuPosition: 'right',
  border: true,
  index: true,
  viewBtn: true,
  selection: true,
  dialogClickModal: false,
  align: 'center',
  indexWidth: 80,
  indexLabel: '编号',
  // menu: false,
  // addBtn: false,
  labelWidth: 145,
  viewBtn: false,
  editBtn: false,
  delBtn: false,
  addBtn: false,
  // menuWidth: 300,
  column: [
    {
      label: '病例名称',
      prop: 'name',
      type: 'input',
      filterable: true,
      overHidden: true,
      // rules: [
      //   {
      //     required: true,
      //     message: '请输入病例名称',
      //     trigger: 'blur',
      //   },
      // ],
    },
    {
      label: '创建时间',
      prop: 'createTime',
      type: 'input',
      filterable: true,
      overHidden: true,
    },
    {
      label: '备注',
      prop: 'remark',
      type: 'textarea',
      minRows: 3,
      maxRows: 5,
      filterable: true,
      overHidden: true,
      span: 24,
    },
  ],
});
const data = ref([]);
let clickMenuValue = ref({});
let isElectricityCaseDialog = ref(false);
let electricityCaseDialogTitle = ref('');
let electricityCaseDialogWidth = ref(500);
let electricityCaseDialogTop = ref('15vh');
let diagnoseRadio = ref('1');
let restInputValue = ref('');
let electricityCaseFileRef = ref(null);
let viewPrintRef = ref(null);

// 操作栏按钮点击
/* 
  type 0：诊断
  type 1：医嘱
  type 2：添加病例
  type 3：添加流程
  type 4：检测报告
  type 5：导出Excel
  type 6：查看并打印
  type 7：电子病例文件
  type 8：修改备注
  type 9：PDF
  type 10：XLS
  type 11：删 除
  type 12：列表病例名称点击
*/
const handleMenu = (type, row = {}, index = null) => {
  clickMenuValue.value = { type, row, index };
  electricityCaseDialogTop.value = '15vh';
  const actions = {
    0: () => {
      diagnoseRadio.value = '1';
      restInputValue.value = '';
      electricityCaseDialogWidth.value = 500;
      electricityCaseDialogTitle.value = '诊断方式';
      isElectricityCaseDialog.value = true;
    },
    1: () => {
      router.push({
        path: '/casemanagement/addCaseForm',
        query: {
          eleMedicalRecordName: '医嘱',
          eleMedicalRecordType: '2',
          ...routerQuery.value,
        },
      });
    },
    2: () => {
      store.commit('SET_TAB', 1);
      router.push({
        path: '/scaleTemplate/index',
        query: {
          isCase: '999',
          caseManagementId: routerQuery.value.caseManagementId,
        },
      });
    },
    3: () => {
      router.push({
        path: '/processlibrary/processLibrary',
        query: {
          groupFlowType: 1,
          isCase: '777',
          caseManagementId: routerQuery.value.caseManagementId,
        },
      });
    },
    4: () => {
      store.commit('SET_TAB', 1);
      router.push({
        path: '/scaleTemplate/index',
        query: {
          isCase: '888',
          caseManagementId: routerQuery.value.caseManagementId,
        },
      });
    },
    6: () => {
      electricityCaseDialogTop.value = '50px';
      electricityCaseDialogWidth.value = 1200;
      electricityCaseDialogTitle.value = '查看并打印';
      isElectricityCaseDialog.value = true;
      nextTick(() => { 
        viewPrintRef.value.open(page.value.total);
      });
    },
    7:() => {
      electricityCaseDialogWidth.value = 1200;
      electricityCaseDialogTitle.value = '查看电子病历文件';
      isElectricityCaseDialog.value = true;
      nextTick(() => {
        electricityCaseFileRef.value.open();
      });
    },
    8: () => {
      diagnoseRadio.value = '1';
      restInputValue.value = '';
      electricityCaseDialogWidth.value = 500;
      electricityCaseDialogTitle.value = '修改备注';
      isElectricityCaseDialog.value = true;
    },
    11: () => {
      crud.value.rowDel(row, index);
    },
    12: () => {
      router.push({
        path: '/casemanagement/addCaseForm',
        query: {
          eleMedicalRecordType: '12',
          eleMedicalRecordId: row.id,
          caseManagementId: routerQuery.value.caseManagementId,
        },
      });
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};

// 弹窗确定点击事件
const dialogSubmit = () => {
  let type = clickMenuValue.value.type;
  let row = clickMenuValue.value.row;
  if (type === 0) {
    router.push({
      path: '/casemanagement/addCaseForm',
      query: {
        eleMedicalRecordName: diagnoseRadio.value == '1' ? '首次诊断' : '复诊',
        eleMedicalRecordType: '1',
        ...routerQuery.value,
      },
    });
  } else if (type === 8) {
    let remarkArr = ['首次诊断', '复 诊', '医 嘱', '检测报告', restInputValue.value];
    let form = {
      id: row.id,
      name: row.name,
      remark: remarkArr[Number(diagnoseRadio.value) - 1],
    };
    if (diagnoseRadio.value === '5' && !restInputValue.value) {
      ElMessage.warning('请填写其他内容！');
      return;
    }
    eleMedicalRecordSubmit(form)
      .then(() => {
        onLoad(page.value);
        ElMessage.success('操作成功!');
        isElectricityCaseDialog.value = false;
      })
      .catch(error => {
        isElectricityCaseDialog.value = false;
      });
  }
};

const rowSave = (row, done, loading) => {
  delete row.informationList;
  add(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowUpdate = (row, index, done, loading) => {
  delete row.informationList;
  update(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return eleMedicalRecordRemove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return eleMedicalRecordRemove(ids.value);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleExport = () => {
  const downloadUrl = `/blade-casemanagement/caseManagement/export-caseManagement?${
    this.website.tokenHeader
  }=${getToken()}`;
  const { name } = this.query;
  let values = {
    name_: name,
  };

  ElMessageBox.confirm('是否导出数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    NProgress.start();
    exportBlob(downloadUrl, values).then(res => {
      downloadXls(res.data, `疾病管理${dateNow()}.xlsx`);
      NProgress.done();
    });
  });
};

const beforeOpen = (done, type) => {
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};

const searchReset = () => {
  query.value = {};
  onLoad(page.value);
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};

const selectionChange = list => {
  selectionList.value = list;
};

const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};

const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};

const refreshChange = () => {
  onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
  loading.value = true;
  let values = {
    descs: 'create_time',
    ...params,
    caseId: routerQuery.value.caseManagementId,
  };
  eleMedicalRecordList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA.records;
    loading.value = false;
    selectionClear();
  });
};
</script>
<style scoped lang="scss">
.electricity-case-content {
  width: 100%;
  height: 100%;
}
.header-btn-content {
  width: 100%;
  height: 35px;
}
.m-dialog-content,
.edit-dialog-content {
  width: 100%;
  height: auto;
  min-height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.edit-dialog-content {
  ::v-deep .el-radio-group {
    width: 170px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  ::v-deep .el-radio {
    margin-bottom: 10px;
  }
}
</style>